package gupaoedu.containerSingleton;

import java.util.HashMap;
import java.util.Map;

/**
 * gupaoedu
 * linwenjie
 * 2019-06-19
 * 容器缓存式单例
 */
public class ContainerSingleton {
    private ContainerSingleton(){

    }

    private static Map<String,Object> ioc = new HashMap<>();

    public static Object getInstance(String className){
        if(!ioc.containsKey(className)){
            synchronized (ContainerSingleton.class) {// 不加会有线程安全的问题
                if(!ioc.containsKey(className)) {
                    Object obj = null;
                    try {
                        obj = Class.forName(className).newInstance();

                        ioc.put(className, obj);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return obj;
                }else {
                    return ioc.get(className);
                }
            }
        }else{
            return ioc.get(className);
        }
    }
}
